//在本文件中可以定义一些函数来帮助我们操控JWT token
//在真实环境中如果使用firebase这种第三方auth服务的话，本文件不需要开发者开发

import { User } from "./types";
const apiUrl = process.env.REACT_APP_API_URL;
const localStrorageKey = "__auth_provider_token__";

export const getToken = ()=>window.localStorage.getItem(localStrorageKey);

export const handleUserResponse = (({user}:{user:User})=>{
    window.localStorage.setItem(localStrorageKey,user.token || '');
    return user;
})

export const login = (data:{username:string,password:string})=>{
    return fetch(`${apiUrl}/login`,{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        body:JSON.stringify(data)
    }).then(async response=>{
        //ok为tru表示成功
        if(response.ok){
            return handleUserResponse(await response.json());
        }else{
            return Promise.reject(await response.json());
        }
    });
}

export const register = (data:{username:string,password:string})=>{
    return fetch(`${apiUrl}/register`,{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        body:JSON.stringify(data)
    }).then(async response=>{
        //ok为tru表示成功
        if(response.ok){
            return handleUserResponse(await response.json());
        }else{
            return Promise.reject(await response.json());
        }
    });
}

export const logout = async ()=>{
    window.localStorage.removeItem(localStrorageKey);
}